package run

import (
	"gitee.com/Luna-CY/hui-hui/internal/application"
	"gitee.com/Luna-CY/hui-hui/internal/interface/runner"
	"gitee.com/Luna-CY/hui-hui/internal/runtime"
	"gitee.com/Luna-CY/hui-hui/internal/toolbox"
	"gitee.com/Luna-CY/hui-hui/server/http"
	"github.com/spf13/cobra"
	"sync"
)

func run(cmd *cobra.Command, _ []string) error {
	// 启动前检查80与443端口是否被占用
	if err := runtime.CheckSystemHttpAndHttpsPort(cmd.Context()); nil != err {
		return err
	}

	// 启动所有的runners
	var runners = []runner.Runner{application.NewCaddy(), toolbox.NewDownloader(), toolbox.NewCrontab(), toolbox.NewProcessor(), http.New(httpListen, httpPort)}

	var wg sync.WaitGroup
	for _, handler := range runners {
		ch, err := handler(cmd.Context())
		if nil != err {
			return err
		}

		wg.Add(1)
		go func() {
			defer wg.Done()

			<-ch
		}()
	}

	wg.Wait()

	return nil
}
